import json
import re
from xml.dom.minidom import Element
import httpx
from parsel import Selector
from .base import BaseParser, VideoAuthor, VideoInfo
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin  # 处理相对路径
import subprocess
import os
from urllib.parse import urljoin
from concurrent.futures import ThreadPoolExecutor
from Crypto.Cipher import AES  # 需要安装 pycryptodome
from .download_m3u8 import download_m3u8
import pickle
import threading
global_lock = threading.Lock()
class AcFun(BaseParser):

    """
    A站：视频地址是m3u8, 可以使用网站 https://tools.thatwind.com/tool/m3u8downloader 下载
    """
    async def parse_share_url(self, share_url: str,idx = 0) -> VideoInfo:
        async with httpx.AsyncClient(follow_redirects=True) as client:
            response = await client.get(share_url, headers=self.get_default_headers())
            response.raise_for_status()
        cleaned_text = re.sub(r'\\+', '', response.text)  # 删除所有连续反斜杠
        soup = BeautifulSoup(response.text, 'html.parser')
        print(soup.head.title)
        file_name = soup.head.title.string
        file_name = file_name.split('|', 1)[0]
        file_name = file_name +'-'+ str(0)+ '.mp4'
        filename = os.path.join('/home/zhubaoohua/work/video_download_py/parse-video-py/','video_mp4/', file_name.replace(" ", "-")) 
        data = []
        # 从文件中读取列表
        with global_lock:
            try:
                with open('data.pkl', 'rb') as file:
                    data = pickle.load(file)
            except FileNotFoundError:
                print("文件未找到")
            except IOError:
                print("读取文件时出错")
        #print(data, sep='\n')  # [1, 2, 3, 4, 5]
        #print(filename)
        video_info = VideoInfo(
            video_url=share_url,
            cover_url=share_url,
            title=soup.head.title,
        )
        if filename in data:
            print(filename+"该电影已下载")
            return video_info
        #with open(f"response.text", "wb") as f:
        #    f.write(response.content)
        #正则表达式过滤出m3u8链接
        port = re.findall(r'[a-zA-Z]+://[^\s]*[.com|.cn]*[.m3u8]+', cleaned_text)
        filtered_list = [s for s in port if re.search(r"m3u8", s)]
        processed_list = [s.split("m3u8", 1)[0] + "m3u8" if "m3u8" in s else s for s in filtered_list]
        tmp_ts_dir = "ts_files"+str(idx)
        if len(processed_list) == 0:
            return video_info
        for i in range(len(processed_list)):
            value_ts = download_m3u8.download_all_ts(processed_list[i],tmp_ts_dir)
            if value_ts is None:
                print("download:"+processed_list[0]+" error")
            else:
                file_name = soup.head.title.string
                file_name = file_name.split('|', 1)[0]
                file_name = file_name +'-'+ str(i)+ '.mp4'
                filename = os.path.join('/home/zhubaoohua/work/video_download_py/parse-video-py/','video_mp4/', file_name.replace(" ", "-")) 
                download_m3u8.merge_ts_files(tmp_ts_dir, filename)
                
                with global_lock:
                    try:
                        with open('data.pkl', 'rb') as file:
                            data = pickle.load(file)
                    except FileNotFoundError:
                        print("文件未找到")
                    except IOError:
                        print("读取文件时出错")
                    with open('data.pkl', 'wb') as file:
                        data.append(filename)
                        pickle.dump(data, file)
                    #print(data)

        return video_info

    async def parse_video_id(self, video_id: str) -> VideoInfo:
        # acid, 格式: ac36935385
        req_url = f"comwiki1.irrrmlro.xyz/archives/{video_id}"
        return await self.parse_share_url(req_url)
